package com.CMS.server;

import java.util.Date;
import java.util.List;

import com.CMS.client.PrivilegeService;
import com.CMS.server.dao.PrivilegeDao;
import com.CMS.server.dao.PrivilegeTypeDao;
import com.CMS.server.dao.PrivilegeViewDao;
import com.CMS.server.domain.Privilege;
import com.CMS.server.domain.PrivilegeType;
import com.CMS.server.domain.PrivilegeView;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class RpcPrivilege extends RemoteServiceServlet implements PrivilegeService{


	private static final long serialVersionUID = -6981893047104951337L;

	@Override
	public List<Privilege> fetch() {
		PrivilegeDao dao = new PrivilegeDao();
		return dao.getAll();
	}

	@Override
	public void create(String description, Long idType, Long idPath) {
		PrivilegeDao dao = new PrivilegeDao();
		PrivilegeTypeDao tdao = new PrivilegeTypeDao();
		PrivilegeViewDao pdao = new PrivilegeViewDao();
		PrivilegeView pv = null;
		PrivilegeType pt = null;
		
		Privilege p = new Privilege();
		p.setDescription(description);
		
		pv = pdao.getEntity(idPath);
		pt = tdao.getEntity(idType);
		
		p.setPath(pv);
		p.setType(pt);
		
		dao.createEntity(p);
	}

	@Override
	public void remove(Long id) {
		PrivilegeDao dao = new PrivilegeDao();
		dao.deleteEntity(dao.getEntity(id));
	}

	@Override
	public void update(String description, boolean flagDelete, Long id,
			String idType, String idPath) {
		
		if(id.compareTo((long) 0) > 0 ){
			PrivilegeDao dao = new PrivilegeDao();
			PrivilegeViewDao vdao = new PrivilegeViewDao();
			PrivilegeTypeDao tdao = new PrivilegeTypeDao();
			
			Privilege p = dao.getEntity(id);
			p.setModDate(new Date());
			p.setFlagDelete(flagDelete);
			p.setDescription(description);
			if(flagDelete)
				p.setDelDate(new Date());
			p.setType(tdao.getEntityByDescription(idType));
			p.setPath(vdao.getEntityByDescription(idPath));
			
			dao.updateEntity(p);
		}
	}
	
}
